/*
 * @Author: wangmyng wangmyng@163.com
 * @Date: 2025-11-02 22:00:53
 * @LastEditors: wangmyng wangmyng@163.com
 * @LastEditTime: 2025-11-09 23:12:48
 */
import { useState, useRef, useEffect } from "react";
import "./index.less";
import { fetchHiddenDangerList } from "@/api/hap";
import DashboardCard from "@/components/pc/DashboardCard";
import { useAppDispatch, useAppSelector } from "@/redux";
import { setDetailWindow, selectDetailWindowVisible } from "@/redux";

interface HiddenDangerCardProps {
  collapsed?: boolean;
}

interface HiddenDangerItem {
  id: string;
  ctime: string;
  hiddenDangerItem: string;
  checkStatus: boolean;
  isRectified: boolean;
  venue: { name: string; link: string; sid: string; sourceValue: string }[];
}

const titleIndexFilterMap = [
  {},
  {
    controlId: "isRectified",
    filterType: 2,
    value: 1,
  },
  {
    controlId: "checkStatus",
    filterType: 2,
    value: "是",
  },
];

/**
 * 首页：隐患列表
 */
const HiddenDangerCard: React.FC<HiddenDangerCardProps> = () => {
  const [dangerList, setDangerList] = useState<HiddenDangerItem[]>([]);
  const [totalCount, setTotalCount] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const listRef = useRef<HTMLDivElement>(null);
  const scrollIntervalRef = useRef<NodeJS.Timeout | null>(null);
  const [titleIndex, setTitleIndex] = useState<number>(0);
  const dispatch = useAppDispatch();
  const detailWindowVisible = useAppSelector(selectDetailWindowVisible);

  useEffect(() => {
    loadingDangerList();
  }, [titleIndex]);

  useEffect(() => {
    if (!dangerList.length) return;
    handleTitleChange(titleIndex);
  }, [dangerList]);

  const loadingDangerList = async () => {
    setLoading(true);
    const filter = titleIndexFilterMap[titleIndex];
    const data = await fetchHiddenDangerList([filter]);
    const rows = data.rows;
    rows.map((item: HiddenDangerItem) => {
      const catStr = item.venue;
      const obj = JSON.parse(catStr);
      item.venue = obj || [];
    });
    setDangerList(rows);
    setTotalCount(data.total);
    setLoading(false);
  };

  const handleTitleChange = (index: number) => {
    setTitleIndex(index);
  };

  // 实现循环滚动效果
  useEffect(() => {
    if (!listRef.current || dangerList.length === 0 || detailWindowVisible) return;

    scrollIntervalRef.current = setInterval(() => {
      const container = listRef.current;
      if (!container) return;
      const currentScrollTop = container.scrollTop;
      const maxScrollTop = container.scrollHeight - container.clientHeight;
      let nextScrollTop = currentScrollTop + 1;
      if (nextScrollTop >= maxScrollTop) {
        nextScrollTop = 0;
      }
      container.scrollTop = nextScrollTop;
    }, 30);

    // 清理定时器
    return () => {
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
        scrollIntervalRef.current = null;
      }
    };
  }, [dangerList.length, detailWindowVisible]);

  // 监听DetailWindow的可见性变化，控制滚动
  useEffect(() => {
    if (detailWindowVisible) {
      // DetailWindow显示时，暂停滚动
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
        scrollIntervalRef.current = null;
      }
    } else {
      // DetailWindow隐藏时，恢复滚动
      startScrolling();
    }
  }, [detailWindowVisible, dangerList.length]);

  // 处理鼠标悬停时暂停滚动
  const handleMouseEnter = () => {
    if (scrollIntervalRef.current) {
      clearInterval(scrollIntervalRef.current);
      scrollIntervalRef.current = null;
    }
  };

  // 启动滚动的函数
  const startScrolling = () => {
    // 如果定时器不存在、有数据且DetailWindow不可见，则重新创建定时器
    if (!scrollIntervalRef.current && dangerList.length > 0 && listRef.current && !detailWindowVisible) {
      scrollIntervalRef.current = setInterval(() => {
        const container = listRef.current;
        if (!container) return;
        const currentScrollTop = container.scrollTop;
        const maxScrollTop = container.scrollHeight - container.clientHeight;
        let nextScrollTop = currentScrollTop + 1;
        if (nextScrollTop >= maxScrollTop) {
          nextScrollTop = 0;
        }
        container.scrollTop = nextScrollTop;
      }, 30);
    }
  };

  // 处理鼠标离开时恢复滚动
  const handleMouseLeave = () => {
    startScrolling();
  };

  const handleItemClick = (item: HiddenDangerItem) => {
    dispatch(
      setDetailWindow({
        title: "隐患详情",
        obj: item,
        x: "37%",
        y: "25%",
        width: "25%",
        height: "25%",
        visible: true,
      })
    );
  };

  return (
    <div className={`hidden-danger-card`}>
      <DashboardCard titles={[`隐患列表(${totalCount})`, "待整改", "已复查"]} onTitleChange={handleTitleChange} loading={loading}>
        <div className="card-content">
          <div className="list-body" ref={listRef} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
            {dangerList.length > 0 || loading ? (
              dangerList.map((item, index) => (
                <div key={item.id} className="list-item" style={{ cursor: "pointer" }} onClick={() => handleItemClick(item)}>
                  <div className="info-col">
                    <div className="info-col address-col">{item.venue?.[0]?.name}</div>
                    <div className="info-col category-col">{item.hiddenDangerItem}</div>
                  </div>
                  <div className="time-col">{item.ctime}</div>
                </div>
              ))
            ) : (
              <div className="empty-list">暂无隐患数据</div>
            )}
          </div>
        </div>
      </DashboardCard>
    </div>
  );
};

export default HiddenDangerCard;
